package point24.util;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;


public class ReversePolishNotation {

    public static final int ERROR = -1;

    static double eval(String[] rpn) {
        return eval(Arrays.asList(rpn));
    }

    static double eval(List<String> rpn) {
        Stack<Double> stack = new Stack<>();
        for (String tok : rpn) {
            if (isNumber(tok)) {
                stack.push(Double.parseDouble(tok));
            } else {
                if (stack.isEmpty()) return ERROR;
                double b = stack.peek();
                stack.pop();
                if (stack.isEmpty()) return ERROR;
                double a = stack.peek();
                stack.pop();
                double c = 0;

                if (tok.equals("+")) {
                    c = a + b;
                } else if (tok.equals("-")) {
                    c = a - b;
                } else if (tok.equals("*")) {
                    c = a * b;

                } else if (b == 0) {
                    return ERROR;
                } else {
                    c = a / b;
                }
                stack.push(c);
            }
        }
        if (stack.size() != 1) return ERROR;
        return stack.peek();
    }

    public static void main(String[] args) {
        double t = eval(Arrays.asList("5 1 5 / - 5 *".split(" ")));
        System.out.println(t);
    }

    public static boolean isNumber(String tok) {
        try {
            Double.parseDouble(tok);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}